<template>
  <view class="page-container w-[750rpx] bg-gray-50 mx-auto">
    <!-- 页面标题 -->
    <view class="page-header bg-[#27c530] text-white p-[30rpx]">
      <text class="text-[32rpx] font-bold">{{ config.pageTitle }}</text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar bg-white m-[24rpx] p-[24rpx] rounded-[20rpx] shadow-md">
      <view class="flex gap-[16rpx]">
        <nut-input v-model="searchForm.name" :placeholder="`搜索${config.searchPlaceholder}`" class="flex-1" />
        <nut-button type="primary" class="bg-[#27c530]" @click="searchRecords">搜索</nut-button>
      </view>
    </view>

    <!-- 记录列表 -->
    <view v-if="records.length === 0" class="empty-container flex flex-col justify-center items-center py-[100rpx]">
      <text class="text-[56rpx] mb-[16rpx]">{{ config.emptyIcon }}</text>
      <text class="text-[32rpx] text-gray-500 mb-[32rpx]">{{ config.emptyText }}</text>
      <nut-button type="primary" class="bg-[#27c530]" @click="goAdd">{{ config.addButtonText }}</nut-button>
    </view>

    <view v-else class="records-container">
      <!-- 使用插槽自定义列表项样式 -->
      <slot name="record-item" :records="records" :config="config" :actions="{ goEdit, deleteRecord, formatDate, getDisplayFields, getFieldLabel }">
        <!-- 默认列表项样式 -->
        <view v-for="record in records" :key="record.id" class="record-card bg-white m-[24rpx] rounded-[20rpx] shadow-md overflow-hidden">
          <view class="record-header p-[24rpx] border-b border-gray-100">
            <view class="flex justify-between items-start">
              <view class="flex items-center">
                <view class="w-[80rpx] h-[80rpx] rounded-full bg-blue-50 flex items-center justify-center mr-[20rpx]">
                  <IconFont :name="config.recordIcon" class="text-[40rpx] text-[#27c530]" />
                </view>
                <view>
                  <text class="text-[28rpx] font-bold text-gray-800">{{ record.name }}</text>
                  <text class="text-[24rpx] text-gray-500 block mt-[4rpx]">档案ID: {{ record.recordid }}</text>
                </view>
              </view>
              <text class="text-[22rpx] text-gray-500">{{ formatDate(record.createTime) }}</text>
            </view>
          </view>

          <view class="record-content p-[24rpx]">
            <view class="flex flex-wrap gap-[12rpx] mb-[16rpx]">
              <view v-for="(value, key) in getDisplayFields(record)" :key="key" class="px-[12rpx] py-[6rpx] bg-green-100 rounded-[8rpx]">
                <text class="text-[22rpx] text-green-700">{{ getFieldLabel(key) }}: {{ value }}</text>
              </view>
            </view>

            <view v-if="record.note" class="mb-[12rpx]">
              <text class="text-[24rpx] text-gray-600">📝 备注：{{ record.note }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="record-actions p-[24rpx] border-t border-gray-100 flex gap-[16rpx]">
            <nut-button size="small" type="primary" class="flex-1 bg-[#27c530]" @click.stop="goEdit(record.id)">编辑</nut-button>
            <nut-button size="small" type="danger" class="flex-1" @click.stop="deleteRecord(record.id)">删除</nut-button>
          </view>
        </view>
      </slot>
    </view>

    <!-- 悬浮添加按钮 -->
    <view class="fab-container fixed bottom-[48rpx] right-[48rpx]">
      <nut-button type="success" class="!w-[90rpx] !h-[90rpx] !p-0 flex items-center justify-center !min-w-[90rpx] min-h-[90rpx] rounded-full bg-[#27c530] shadow-lg" @click="goAdd">
        <template #icon>
          <IconFont name="plus" size="24" class="text-[48rpx] text-white" />
        </template>
      </nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { request } from '@/service/request'
import { IconFont } from '@nutui/icons-vue-taro'
import { localStg } from '@/utils'

interface CrudConfig {
  pageTitle: string
  searchPlaceholder: string
  emptyIcon: string
  emptyText: string
  addButtonText: string
  recordIcon: string
  listApi: string
  addApi: string
  editApi: string
  deleteApi: string
  queryByIdApi: string
  fieldConfig: any
  addRoute: string
  editRoute: string
  viewRoute?: string
  displayFields?: string[]
}

interface Props {
  config: CrudConfig
}

const props = defineProps<Props>()

const records = ref<any[]>([])
const searchForm = reactive({
  recordid: '',
  name: ''
})

onMounted(() => {
  const obj = localStg.get("demographicInfo");
  if(obj){
    searchForm.recordid = obj.recordid;
  }
  loadRecords()
})

async function loadRecords() {
  try {
    const result = await request.get<any>(props.config.listApi, {}, {
      useErrMsg: true
    })
    
    if (result.success?.records) {
      records.value = result.success.records || []
    } else if (result.success) {
      records.value = result.success || []
    } else {
      records.value = result || []
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

function searchRecords() {
  loadRecords()
}

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

function goAdd() {
  Taro.navigateTo({
    url: props.config.addRoute
  })
}

function goEdit(id: string) {
  Taro.navigateTo({
    url: `${props.config.editRoute}?id=${id}`
  })
}

async function deleteRecord(id: string) {
  try {
    const result = await Taro.showModal({
      title: '确认删除',
      content: `确定要删除这条${props.config.pageTitle}记录吗？`,
      confirmText: '删除',
      cancelText: '取消'
    })
    
    if (result.confirm) {
      await request.delete(`${props.config.deleteApi}?id=${id}`, {}, {
        useErrMsg: true
      })
      
      Taro.showToast({ title: '删除成功', icon: 'success' })
      loadRecords()
    }
  } catch (error) {
    console.error('删除失败:', error)
    Taro.showToast({ title: '删除失败', icon: 'error' })
  }
}

function getDisplayFields(record: any) {
  const displayFields = props.config.displayFields || ['name']
  const result: any = {}
  
  displayFields.forEach(field => {
    if (record[field] && field !== 'name' && field !== 'recordid' && field !== 'createTime') {
      result[field] = record[field]
    }
  })
  
  return result
}

function getFieldLabel(fieldKey: string) {
  const fieldConfig = props.config.fieldConfig[fieldKey]
  return fieldConfig ? fieldConfig.label : fieldKey
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
}

.page-header {
  border-radius: 0 0 20rpx 20rpx;
}

.search-bar {
  border-radius: 20rpx;
}

.record-card {
  transition: all 0.3s ease;
}

.record-card:active {
  transform: scale(0.98);
}

.fab-container {
  z-index: 1000;
}

.empty-container {
  min-height: 400rpx;
}

.records-container {
  padding-bottom: 120rpx;
}
</style>
